import React, { useState, useEffect } from 'react';
import { 
  Container, 
  Box, 
  Typography, 
  TextField, 
  Button, 
  Grid, 
  Card, 
  CardContent,
  ThemeProvider,
  createTheme,
  CircularProgress,
  Paper
} from '@mui/material';
import axios from 'axios';
import WbSunnyIcon from '@mui/icons-material/WbSunny';
import CloudIcon from '@mui/icons-material/Cloud';
import WaterDropIcon from '@mui/icons-material/WaterDrop';
import AirIcon from '@mui/icons-material/Air';
import AcUnitIcon from '@mui/icons-material/AcUnit';
import { createPortal } from 'react-dom';

const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
    secondary: {
      main: '#dc004e',
    },
  },
});

const API_CONFIG = {
  baseURL: 'https://jisutqybmf.market.alicloudapi.com/weather/query',
  headers: {
    'Authorization': 'APPCODE 8bbd4b7715ae405bac2da49d4d28cbbf',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
};

function WeatherCardPortal({ children, isHovered, cardRef }) {
  const [portalContainer, setPortalContainer] = useState(null);

  useEffect(() => {
    if (isHovered) {
      const container = document.createElement('div');
      container.style.position = 'fixed';
      container.style.zIndex = '9999';
      container.style.pointerEvents = 'none';
      document.body.appendChild(container);
      setPortalContainer(container);

      return () => {
        document.body.removeChild(container);
      };
    }
  }, [isHovered]);

  if (!isHovered || !portalContainer) {
    return children;
  }

  const rect = cardRef.current.getBoundingClientRect();
  const portalStyle = {
    position: 'fixed',
    top: rect.top,
    left: rect.left,
    width: rect.width,
    height: rect.height,
    transform: 'scale(1.08)',
    transformOrigin: 'center center',
    pointerEvents: 'auto',
    transition: 'transform 0.2s',
  };

  return createPortal(
    <div style={portalStyle}>
      {children}
    </div>,
    portalContainer
  );
}

function App() {
  const [city, setCity] = useState('');
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [hoveredCardIndex, setHoveredCardIndex] = useState(null);
  const cardRefs = React.useRef([]);

  const fetchWeatherData = async () => {
    if (!city) return;
    
    setLoading(true);
    setError('');
    
    try {
      const response = await axios.get(API_CONFIG.baseURL, {
        headers: API_CONFIG.headers,
        params: { city }
      });
      
      setWeatherData(response.data);
    } catch (err) {
      setError('获取天气数据失败，请重试。');
      console.error('Error fetching weather data:', err);
    } finally {
      setLoading(false);
    }
  };

  const getWeatherIcon = (weather) => {
    if (weather.includes('晴')) return <WbSunnyIcon sx={{ fontSize: 40, color: '#FFD700' }} />;
    if (weather.includes('雨')) return <WaterDropIcon sx={{ fontSize: 40, color: '#1E90FF' }} />;
    if (weather.includes('云')) return <CloudIcon sx={{ fontSize: 40, color: '#A9A9A9' }} />;
    if (weather.includes('雪')) return <AcUnitIcon sx={{ fontSize: 40, color: '#B0E0E6' }} />;
    return <AirIcon sx={{ fontSize: 40, color: '#87CEEB' }} />;
  };

  function getRainProbabilityByWeather(weather) {
    if (!weather) return '20%';
    if (weather.includes('雨')) return '80%';
    if (weather.includes('雪')) return '60%';
    if (weather.includes('多云')) return '30%';
    if (weather.includes('阴')) return '40%';
    if (weather.includes('晴')) return '10%';
    return '20%';
  }

  return (
    <ThemeProvider theme={theme}>
      <Box sx={{ 
        minHeight: '100vh',
        background: 'linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%)',
        py: 4
      }}>
        <Container maxWidth="lg">
          <Paper elevation={3} sx={{ p: 4, borderRadius: 2 }}>
            <Box sx={{ textAlign: 'center', mb: 4 }}>
              <Typography variant="h3" component="h1" gutterBottom sx={{ color: '#1976d2' }}>
                天气预报
              </Typography>
              
              <Box sx={{ mb: 4 }}>
                <TextField
                  label="输入城市名称"
                  variant="outlined"
                  value={city}
                  onChange={(e) => setCity(e.target.value)}
                  sx={{ mr: 2, width: '300px' }}
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                      fetchWeatherData();
                    }
                  }}
                />
                <Button 
                  variant="contained" 
                  onClick={fetchWeatherData}
                  disabled={loading}
                  sx={{ height: '56px' }}
                >
                  查询天气
                </Button>
              </Box>

              {loading && (
                <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
                  <CircularProgress />
                </Box>
              )}

              {error && (
                <Typography color="error" sx={{ my: 2 }}>
                  {error}
                </Typography>
              )}

              {weatherData && (
                <Grid container spacing={3}>
                  {weatherData.result.forecast.map((day, index) => {
                    const isHovered = hoveredCardIndex === index;
                    const cardRef = React.useRef(null);
                    cardRefs.current[index] = cardRef;

                    // 计算降水概率（根据天气状况估算）
                    const getRainProbability = (weather) => {
                      if (weather.includes('雨')) return '80%';
                      if (weather.includes('多云')) return '30%';
                      if (weather.includes('阴')) return '40%';
                      if (weather.includes('晴')) return '10%';
                      return '20%';
                    };

                    return (
                      <Grid item xs={12} sm={6} md={4} key={index}>
                        <WeatherCardPortal 
                          isHovered={isHovered}
                          cardRef={cardRef}
                        >
                          <Card 
                            ref={cardRef}
                            sx={{ 
                              height: '100%',
                              transition: 'transform 0.2s',
                              '&:hover': {
                                transform: 'scale(1.08)',
                              }
                            }}
                            onMouseEnter={() => setHoveredCardIndex(index)}
                            onMouseLeave={() => setHoveredCardIndex(null)}
                          >
                            <CardContent>
                              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                                {getWeatherIcon(day.weather)}
                                <Typography variant="h6" sx={{ ml: 1 }}>
                                  {day.weather}
                                </Typography>
                              </Box>
                              <Typography variant="h5" gutterBottom>
                                {day.date}
                              </Typography>
                              <Typography color="textSecondary" sx={{ mb: 1 }}>
                                温度: {day.low} ~ {day.high}
                              </Typography>
                              <Typography color="textSecondary" sx={{ mb: 1 }}>
                                风向: {day.wind}
                              </Typography>
                              <Typography sx={{ fontSize: '0.8rem', mb: 0.2 }}>
                                {day.pop !== undefined ? `${day.pop}%` : getRainProbabilityByWeather(day.weather)}
                              </Typography>
                            </CardContent>
                          </Card>
                        </WeatherCardPortal>
                      </Grid>
                    );
                  })}
                </Grid>
              )}
            </Box>
          </Paper>
        </Container>
      </Box>
    </ThemeProvider>
  );
}

export default App; 